package org.nowcoder.leetcode.sort;


import java.util.PriorityQueue;

/**
 * Title  : 215. Kth Largest Element in an Array
 * Source : https://leetcode.cn/problems/kth-largest-element-in-an-array/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-07-18
 */

public class LeetCode_215 {
    public int findKthLargest(int[] nums, int k) {
        //暴力解法：排序
        // Arrays.sort(nums);
        // return nums[nums.length - k];

        //最小堆 --- Top k
        PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
        for (int i = 0; i < nums.length; i++) {
            if (i < k) {
                minHeap.add(nums[i]);
            } else {
                if (!minHeap.isEmpty() && minHeap.peek() < nums[i]) {
                    minHeap.poll();
                    minHeap.add(nums[i]);
                }
            }
        }
        return minHeap.peek();
    }
}
